package com.example.demo.rsa;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.RSA;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
import org.junit.Test;

import java.io.IOException;
import java.io.StringWriter;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

public class Test4 {

    @Test
    public void getRSA() {

        RSA rsa = SecureUtil.rsa();
        RSAPrivateKey privateKey = (RSAPrivateKey) rsa.getPrivateKey();
        RSAPublicKey publicKey = (RSAPublicKey) rsa.getPublicKey();

        StringWriter writer = new StringWriter();
        PemWriter pemWriter = new PemWriter(writer);

        String publicKeyBase64 = "";
        String privateKeyBase64 = "";

        try {
            pemWriter.writeObject(new PemObject("PUBLIC KEY", publicKey.getEncoded()));
            pemWriter.flush();
            publicKeyBase64 = writer.toString();
            System.out.println("生成的公钥：" + publicKeyBase64);

            writer = new StringWriter();
            pemWriter = new PemWriter(writer);
            pemWriter.writeObject(new PemObject("RSA PRIVATE KEY", privateKey.getEncoded()));
            pemWriter.flush();
            privateKeyBase64 = writer.toString();
            System.out.println("生成的私钥：" + privateKeyBase64);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                pemWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
